#include "LinkedList.h"
// Edit by PassLink.cn
// 构造函数，初始化链表为空
namespace ns3
{
LinkedList::LinkedList() {
    head = nullptr;
}

// 插入节点函数，在链表末尾插入
void LinkedList::insert(string key, int32_t value) {
    Link_Node* newNode = new Link_Node; // 创建新节点
    newNode->key = key;
    newNode->value = value;
    newNode->next = nullptr;
    if (head == nullptr) {
        head = newNode; // 如果链表为空，新节点成为头节点
    } else {
        Link_Node* temp = head;
        while (temp->next != nullptr) {
            temp = temp->next; // 找到链表的末尾节点
        }
        temp->next = newNode; // 将新节点链接到末尾节点的后面
    }
}

// 删除节点函数，删除第一个匹配到的键
void LinkedList::remove(string key) {
    if (head == nullptr) {
        cout << "链表为空，无法删除节点" << endl;
        return;
    }

    if (head->key == key) {
        Link_Node* temp = head;
        head = head->next; // 如果要删除的节点是头节点，直接移动头指针
        delete temp; // 释放节点内存
        return;
    }

    Link_Node* prev_node = head;
    Link_Node* curr_node = head->next;
    while (curr_node != nullptr) {
        if (curr_node->key == key) {
            prev_node->next = curr_node->next; // 找到要删除的节点，修改前一个节点的指针跳过当前节点
            delete curr_node; // 释放节点内存
            return;
        }
        prev_node = curr_node;
        curr_node = curr_node->next;
    }

    cout << "未找到要删除的节点" << endl;
}

// 清空链表
// 清空链表
void LinkedList::clear() {
    Link_Node* curr_node = head;
    while (curr_node != nullptr) {
        Link_Node* temp = curr_node;
        curr_node = curr_node->next;
        delete temp; // 释放节点内存
    }
    head = nullptr; // 头指针指向空指针，链表为空
}

// 打印链表函数
void LinkedList::print() {
    Link_Node* temp = head;
    cout << "链表内容：" << endl;
    while (temp != nullptr) {
        cout << "(" << temp->key << ", " << temp->value << ") ";
        temp = temp->next;
    }
    cout << endl;
}
}